<template>
    <!-- <h1>用户列表</h1> -->
    <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
        <el-row :gutter="20">
            <el-col :span="10">
                <el-input v-model="user_data.queryName" placeholder="请输入要搜索的账号" class="input-with-select">
                    <template #append>
                        <el-button :icon="Search" @click="searchUser" />
                    </template>
                </el-input>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" :icon="CirclePlusFilled" @click="adduserflag = true">
                    添加用户
                </el-button>
            </el-col>
            <!-- <el-col :span="2">
                <el-button type="primary" :icon="RemoveFilled">删除用户</el-button>
            </el-col> -->
        </el-row>
        <el-row>
            <el-table :data="user_data.tableData" stripe class="gap">
                <el-table-column prop="id" label="id" width="80" />
                <el-table-column prop="name" label="账户" width="80" />
                <el-table-column prop="nick_name" label="昵称" />
                <el-table-column prop="phone" label="手机号" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="role_name" label="角色" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        <el-button size="small" type='success' @click="handlerest(scope.$index, scope.row)">重置</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <el-pagination v-model:current-page="user_data.pageNum" v-model:page-size="user_data.pageSize"
            :page-sizes="pageSizes" :small="small" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="user_data.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" class="gap" />
    </el-card>

    <!-- 增加用户对话框 -->
    <el-dialog v-model="adduserflag" title="增加用户" :before-close="addFormRest">
        <el-form :model="user_form" :rules="user_rules" ref="addFormRef">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="user_form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="pwd">
                <el-input v-model="user_form.pwd" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" :label-width="formLabelWidth" prop="real_pwd">
                <el-input v-model="user_form.real_pwd" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
                <el-input v-model="user_form.nick_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                <el-input v-model="user_form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                <el-input v-model="user_form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth" prop="role_id">
                <el-select v-model="user_form.role_id" placeholder="请选择角色">
                    <el-option :label="r.name" :value="r.id" v-for="r in roles" :key="r.id"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addFormRest">取消</el-button>
                <el-button type="primary" @click="addUser(addFormRef)">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑用户 -->
    <!-- 编辑用户对话框 -->
    <!-- //:before-close="editFormRef" -->
    <el-dialog v-model="edituserflag" title="编辑用户">
        <el-form :model="edit_form" ref="editFormRef">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="edit_form.name" autocomplete="off" disabled />
            </el-form-item>

            <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
                <el-input v-model="edit_form.nick_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                <el-input v-model="edit_form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                <el-input v-model="edit_form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth" prop="role_id">
                <el-select v-model="edit_form.role_id" placeholder="请选择角色">
                    <el-option :label="r.name" :value="r.id" v-for="r in roles" :key="r.id"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="edituserflag = false">取消</el-button>
                <el-button type="primary" @click="editUser">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 删除用户 -->
    <el-dialog v-model="deluserflag" title="删除用户">
        <span>确定要删除账号:<b>{{ del_user.name }}</b>昵称：<b>{{ del_user.nick_name }}</b>的用户</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="deluserflag = false">取消</el-button>
                <el-button type="primary" @click="delUser">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog v-model="restuserflag" title="重置密码">
        <span>确定要重置账号:<b>{{ rest_user.name }}</b>昵称：<b>{{ rest_user.nick_name }}</b>的用户</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="restuserflag = false">取消</el-button>
                <el-button type="primary" @click="restUserPwd">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ArrowRight } from '@element-plus/icons-vue'
import { Search, CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import api from '@/api/index.js'
import { onMounted, reactive, ref } from 'vue';

const user_data = reactive({
    tableData: [],
    total: 0,
    pageNum: 1,
    pageSize: 2,
    queryName: ''
})
const adduserflag = ref(false)
const edituserflag = ref(false)
const deluserflag = ref(false)
const restuserflag = ref(false)
const formLabelWidth = '140px'
const addFormRef = ref(null)
const editFormRef = ref(null)
let roles=ref([])
const user_form = reactive({
    name: '',
    pwd: null,
    real_pwd: null,
    nick_name: null,
    phone: null,
    email: null,
    role_id:null
})

let edit_form = reactive({
    name: '',
    nick_name: null,
    phone: null,
    email: null,
    role_id:null
})

let del_user = reactive({
    id: null,
    name: null,
    nick_name: null
})

let rest_user = reactive({
    id: null,
    name: null,
    nick_name: null
})
// 确认密码规则
const validatePass2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请确认密码'))
    } else if (value !== user_form.pwd) {
        callback(new Error("密码不匹配"))
    } else {
        callback()
    }
}

const validatephone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!/^1[3456789]\d{9}/.test(value)) {
        callback(new Error("手机号违规"))
    } else {
        callback()
    }
}

const validateemail = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入邮箱'))
    } else if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/i.test(value)) {
        callback(new Error("邮箱违规"))
    } else {
        callback()
    }
}
//校验用户表单数据
const user_rules = reactive({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '长度3~10', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { min: 6, max: 18, message: '密码长度6~18', trigger: 'blur' }
    ],
    real_pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
    ],
    nick_name: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 3, max: 5, message: '长度3~5', trigger: 'blur' }
    ],
    phone: [
        { validator: validatephone, trigger: 'blur' }
    ],
    email: [
        { validator: validateemail, trigger: 'blur' }
    ]
})
let pageSizes = ref([1, 2, 5, 10])
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let userId = ref(0)
onMounted(() => {
    get_user_list()
    get_roles()
})

const get_user_list = () => {
    let params = {
        'pnum': user_data.pageNum,
        'psize': user_data.pageSize,
        'name': user_data.queryName
    }
    api.get_user_list({ params }).then(res => {
        // console.log(res)
        // 更新用户列表数据
        user_data.tableData = res.data.data.data
        // 更新分页数据总数
        user_data.total = res.data.data.total
    })
}

const handleSizeChange = (val) => {
    //修改每页显示多少条数据
    user_data.pageSize = val
    // 重新获取列表数据
    get_user_list()
}

const handleCurrentChange = (val) => {
    // 显示第几页数据
    user_data.pageNum = val
    // 重新获取列表数据
    get_user_list()
}

const searchUser = () => {
    // 初始化
    user_data.pageNum = 1
    get_user_list()
}

const addFormRest = () => {
    // 重置表单
    addFormRef.value.resetFields()
    // 关闭
    adduserflag.value = false
}

// 添加用户
const addUser = (formRef) => {
    formRef.validate((valid) => {
        if (valid) {
            console.log('信息正确')
            api.add_user(user_form).then(res => {
                //根据结果处理
                if (res.data.status == 200) {
                    ElMessage({
                        message: res.data.msg,
                        type: 'success',
                    })
                    addFormRest()
                    get_user_list()
                }
                else {
                    ElMessage({
                        message: res.data.msg,
                        type: 'warning',
                    })
                }
            })
        }
        else {
            console.log('提交错误!')
            return false
        }
    })
}

// 编辑用户
const handleEdit = (index, row) => {
    // console.log(index, row)
    edituserflag.value = true
    userId.value = row.id
    // edit_form=row  //从当前表单
    //从数据库获取
    api.get_user_by_id(row.id).then(res => {
        // edit_form=res.data.data 速度慢
        edit_form.name = res.data.data.name
        edit_form.nick_name = res.data.data.nick_name
        edit_form.phone = res.data.data.phone
        edit_form.email = res.data.data.email
        edit_form.role_id = res.data.data.role_id
    })
}

const editUser = () => {
    api.edit_user(userId.value, edit_form).then(res => {
        if (res.data.status == 200) {
            ElMessage({
                message: res.data.msg,
                type: 'success',
            })
            edituserflag.value = false
            get_user_list()
        } else {
            ElMessage({
                message: res.data.msg,
                type: 'warning',
            })
        }
    })
}

const handleDelete = (index, row) => {
    del_user.id = row.id
    del_user.name = row.name
    del_user.nick_name = row.nick_name

    deluserflag.value = true
}
// 删除用户
const delUser = () => {
    // 调用接口
    api.del_user(del_user.id).then(res => {
        if (res.data.status == 200) {
            ElMessage({
                message: res.data.msg,
                type: 'success',
            })
            deluserflag.value = false
            get_user_list()
        } else {
            ElMessage({
                message: res.data.msg,
                type: 'warning',
            })
        }
    })
}

// 重置窗口
const handlerest = (index, row) => {
    rest_user.id = row.id
    rest_user.name = row.name
    rest_user.nick_name = row.nick_name

    restuserflag.value = true
}
// 提交
const restUserPwd = () => {
    api.rest_user(rest_user.id).then(res => {
        if (res.data.status == 200) {
            ElMessage({
                message: res.data.msg,
                type: 'success',
            })
            restuserflag.value = false
            get_user_list()
        } else {
            ElMessage({
                message: res.data.msg,
                type: 'warning',
            })
        }
    })
}
// 获取角色列表
const get_roles=()=>{
    api.get_roles().then(res=>{
        roles=res.data.data
    })
}

</script>

<style scoped>
.box-card {
    margin-top: 25px;
}

.gap {
    margin-top: 10px;
}
</style>